package com.xxq.semester.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxq.semester.entity.utils.ResponseEntity;
import com.xxq.semester.entity.user.Users;
import com.xxq.semester.service.user.IUsersService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 后台用户信息表 前端控制器
 * </p>
 *
 * @author saki
 * @since 2025-07-13
 */
@RestController
@RequestMapping("/api/users")
@Tag(name = "用户管理", description = "用户增删改查接口")
public class UsersController {

    @Autowired
    private IUsersService usersService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 分页查询用户列表
     */
    @GetMapping("/page")
    @Operation(summary = "分页查询用户列表", description = "支持按用户名、邮箱、角色等条件分页查询用户")
    public ResponseEntity<IPage<Users>> getUserPage(
            @Parameter(description = "页码，从1开始") @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "用户名（模糊查询）") @RequestParam(required = false) String username,
            @Parameter(description = "邮箱（模糊查询）") @RequestParam(required = false) String email,
            @Parameter(description = "角色（?）") @RequestParam(required = false) String role,
            @Parameter(description = "是否活动（?）") @RequestParam(required = false) Integer isActive) {
        
        Page<Users> page = new Page<>(current, size);
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        
        // 添加查询条件
        if (StringUtils.hasText(username)) {
            queryWrapper.like("username", username);
        }
        if (StringUtils.hasText(email)) {
            queryWrapper.like("email", email);
        }
        if (StringUtils.hasText(role)) {
            queryWrapper.eq("role", role);
        }
        if (isActive != null) {
            queryWrapper.eq("is_active", isActive);
        }
        
        // 按创建时间倒序排列
        queryWrapper.orderByDesc("created_at");
        
        IPage<Users> userPage = usersService.page(page, queryWrapper);
        
        // 隐藏密码字段
        userPage.getRecords().forEach(user -> user.setPassword(null));
        
        return ResponseEntity.success(userPage);
    }

    /**
     * 获取所有用户列表（不分页）
     */
    @GetMapping
    @Operation(summary = "获取所有用户列表", description = "获取所有活动用户列表")
    public ResponseEntity<List<Users>> index() {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("created_at");
        
        List<Users> userList = usersService.list(queryWrapper);
        
        // 隐藏密码字段
        userList.forEach(user -> user.setPassword(null));
        
        return ResponseEntity.success(userList);
    }

    /**
     * 根据ID查询用户
     */
    @GetMapping("/{id}")
    @Operation(summary = "根据ID查询用户", description = "根据用户ID获取用户详细信息")
    public ResponseEntity<Users> getUserById(
            @Parameter(description = "用户ID") @PathVariable Integer id) {
        
        Users user = usersService.getById(id);
        if (user == null) {
            return ResponseEntity.fail("用户不存在");
        }
        
        // 隐藏密码字段
        user.setPassword(null);
        
        return ResponseEntity.success(user);
    }

    /**
     * 根据用户名查询用户
     */
    @GetMapping("/username/{username}")
    @Operation(summary = "根据用户名查询用户", description = "根据用户名获取用户信息")
    public ResponseEntity<Users> getUserByUsername(
            @Parameter(description = "用户名") @PathVariable String username) {
        
        Users user = usersService.getUserByUsername(username);
        if (user == null) {
            return ResponseEntity.fail("用户不存在");
        }
        
        // 隐藏密码字段
        user.setPassword(null);
        
        return ResponseEntity.success(user);
    }

    /**
     * 添加用户
     */
    @PostMapping
    @Operation(summary = "添加用户", description = "创建新用户")
    public ResponseEntity<String> addUser(@RequestBody Users user) {
        // 参数验证
        if (!StringUtils.hasText(user.getUsername())) {
            return ResponseEntity.fail("用户名不能为空");
        }
        if (!StringUtils.hasText(user.getPassword())) {
            return ResponseEntity.fail("密码不能为空");
        }
        if (!StringUtils.hasText(user.getEmail())) {
            return ResponseEntity.fail("邮箱不能为空");
        }
        
        // 检查用户名是否已存在
        if (usersService.getUserByUsername(user.getUsername()) != null) {
            return ResponseEntity.fail("用户名已存在");
        }
        
        // 检查邮箱是否已存在
        if (usersService.getUserByEmail(user.getEmail()) != null) {
            return ResponseEntity.fail("邮箱已被注册");
        }
        
        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        
        // 设置默认值
        if (user.getRole() == null) {
            user.setRole("2"); // 默认为老师
        }

        user.setLastUpdate(LocalDateTime.now());
        
        boolean success = usersService.save(user);
        
        if (success) {
            return ResponseEntity.success("用户添加成功");
        } else {
            return ResponseEntity.fail("用户添加失败");
        }
    }

    /**
     * 修改用户
     */
    @PutMapping("/{id}")
    @Operation(summary = "修改用户", description = "根据ID更新用户信息")
    public ResponseEntity<String> updateUser(
            @Parameter(description = "用户ID") @PathVariable Integer id,
            @RequestBody Users user) {
        
        // 检查用户是否存在
        Users existingUser = usersService.getById(id);
        if (existingUser == null) {
            return ResponseEntity.fail("用户不存在");
        }
        
        // 如果修改了用户名，检查是否重复
        if (StringUtils.hasText(user.getUsername()) && 
            !user.getUsername().equals(existingUser.getUsername())) {
            Users userWithSameUsername = usersService.getUserByUsername(user.getUsername());
            if (userWithSameUsername != null && !userWithSameUsername.getId().equals(id)) {
                return ResponseEntity.fail("用户名已存在");
            }
        }
        
        // 如果修改了邮箱，检查是否重复
        if (StringUtils.hasText(user.getEmail()) && 
            !user.getEmail().equals(existingUser.getEmail())) {
            Users userWithSameEmail = usersService.getUserByEmail(user.getEmail());
            if (userWithSameEmail != null && !userWithSameEmail.getId().equals(id)) {
                return ResponseEntity.fail("邮箱已被注册");
            }
        }
        
        // 设置ID和更新时间
        user.setId(id);
        user.setLastUpdate(LocalDateTime.now());
        
        // 如果密码不为空，则加密
        if (StringUtils.hasText(user.getPassword())) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        } else {
            // 保持原密码
            user.setPassword(existingUser.getPassword());
        }
        
        boolean success = usersService.updateById(user);
        
        if (success) {
            return ResponseEntity.success("用户修改成功");
        } else {
            return ResponseEntity.fail("用户修改失败");
        }
    }

    /**
     * 物理删除用户
     */
    @DeleteMapping("/{id}/force")
    @Operation(summary = "物理删除用户", description = "根据ID物理删除用户（危险操作）")
    public ResponseEntity<String> forceDeleteUser(
            @Parameter(description = "用户ID") @PathVariable Integer id) {
        
        // 检查用户是否存在
        if (usersService.getById(id) == null) {
            return ResponseEntity.fail("用户不存在");
        }
        
        boolean success = usersService.removeById(id);
        
        if (success) {
            return ResponseEntity.success("用户物理删除成功");
        } else {
            return ResponseEntity.fail("用户物理删除失败");
        }
    }

    /**
     * 批量删除用户（逻辑删除）
     */
    @DeleteMapping("/batch")
    @Operation(summary = "批量删除用户", description = "批量逻辑删除用户")
    public ResponseEntity<String> batchDeleteUsers(
            @Parameter(description = "用户ID列表") @RequestBody List<Integer> ids) {
        
        if (ids == null || ids.isEmpty()) {
            return ResponseEntity.fail("请选择要删除的用户");
        }
        
        // 查询所有要删除的用户
        List<Users> users = usersService.listByIds(ids);
        if (users.isEmpty()) {
            return ResponseEntity.fail("没有找到要删除的用户");
        }
        
        // 设置为非活动状态
        users.forEach(user -> {
            user.setLastUpdate(LocalDateTime.now());
        });
        
        boolean success = usersService.updateBatchById(users);
        
        if (success) {
            return ResponseEntity.success("批量删除成功，共删除" + users.size() + "个用户");
        } else {
            return ResponseEntity.fail("批量删除失败");
        }
    }

    /**
     * 重置用户密码
     */
    @PutMapping("/{id}/reset-password")
    @Operation(summary = "重置用户密码", description = "重置指定用户的密码")
    public ResponseEntity<String> resetPassword(
            @Parameter(description = "用户ID") @PathVariable Integer id,
            @Parameter(description = "新密码") @RequestParam String newPassword) {
        
        if (!StringUtils.hasText(newPassword)) {
            return ResponseEntity.fail("新密码不能为空");
        }
        
        // 检查用户是否存在
        Users user = usersService.getById(id);
        if (user == null) {
            return ResponseEntity.fail("用户不存在");
        }
        
        // 更新密码
        user.setPassword(passwordEncoder.encode(newPassword));
        user.setLastUpdate(LocalDateTime.now());
        
        boolean success = usersService.updateById(user);
        
        if (success) {
            return ResponseEntity.success("密码重置成功");
        } else {
            return ResponseEntity.fail("密码重置失败");
        }
    }


}
